<template>
    <div>
        <div :id="id" class="st-table"></div>
    </div>
</template>

<script>
import 'handsontable-pro/languages/zh-CN.js';
import Handsontable from 'handsontable-pro';
import 'handsontable-pro/dist/handsontable.full.css';
import Hash from "../../lib/hash";
import {mapMutations, mapGetters} from 'vuex';

//dom操作
class Dom{

    /**
     * 隐藏掉License
     */
    static hideLicense(){
        let license=document.getElementById('hot-display-license-info');
        license.remove();
    }

    static autoHight(){
        let stTable=document.getElementsByClassName('st-table');
        for(let i=0;i<stTable.length;i++){
            stTable[i].style.height=(window.innerHeight-115)+'px';
            stTable[i].style.width=(window.innerWidth*.8-0)+'px';
        }
    }
    
}

export default {
    props:{

        //settings中初始时不能包含mergeCells,否则将导致公式元数据丢失，而只留下计算结果
        settings:{
            type:Object,
            default:()=>{
                return {};
            },
        },
        preMergeCells:{
            type:Array,
            default:()=>{
                return [];
            },
        },
        active:{
            type:Boolean,
            default:false
        },
        index:{
            type:Number,
            default:0
        }
    },
    created(){
        this.id='st'+new Hash().gethashcode();//获取一个随机不重复值作为id
    },
    mounted(){
        //表格实例化
        this.el=document.getElementById(this.id);
        this.hs = new Handsontable(this.el, this.settings);
        this.activateCurrentTable();//将当前表格推送为全局激活表格（以便在其它组件里方便调用）
        
        Dom.hideLicense();
        Dom.autoHight();

        Handsontable.hooks.add('afterMergeCells', this.afterMergeCells, this.hs);
        Handsontable.hooks.add('afterUnmergeCells', this.afterUnmergeCells, this.hs);
        Handsontable.hooks.add('afterChange', this.afterChange, this.hs);
        Handsontable.hooks.add('afterDocumentKeyDown',this.afterDocumentKeyDown,this.hs);
        Handsontable.hooks.add('afterSelection',this.afterSelection,this.hs);
        Handsontable.hooks.add('afterColumnResize',this.afterColumnResize,this.hs);
        Handsontable.hooks.add('afterRowResize',this.afterRowResize,this.hs);

        this.hs.render(); 
    },
    destroyed(){
        this.hs.destroy();
    },
    data(){
        return {
            id:'',
            el:'', //Dom element 
            hs:'', //储存 handsontable 实例
            sourceData:[],
            mergeCells:[],
        }
    },
    watch:{

        active(newVal,oldVal){
            if(newVal){
               this.hs.render(); 
               this.activateCurrentTable();
            }
        },

        //再内部table发生变化时，自动同步值到store对象
        sourceData(newVal,oldVal){
            this.updateTableData({
                index:this.index,
                data:newVal
            });
        },

        mergeCells(newVal,oldVal){
            this.updateTableMergeCells({
                index:this.index,
                data:newVal
            });
        },

        settings:{
            handler(newVal,oldVal){
                this.settings=newVal;
                this.hs.getPlugin('Formulas').disablePlugin();
                this.hs.getPlugin('Formulas').enablePlugin();
                this.hs.getPlugin('Formulas').recalculateFull();
                //this.hs.getPlugin('Formulas').recalculateOptimized();
            },
            deep:true
        }
    },
    computed:{
        ...mapGetters(['getTables'])
    },
    methods:{
        ...mapMutations([
            'updateTable',
            'updateTableData',
            'setCurrentTable',
            'updateTableMergeCells',
            'setRowColNumber',
            'updateSize'
        ]),
        activateCurrentTable(){
            this.setCurrentTable({
                id:this.id,
                index:this.index,
                hs:this.hs,
                table:this.getTables[this.index]
            });
        },


        /**
         * 下列为勾子函数的实现
         */

        //数据发送改变
        afterChange(e,v){
            this.sourcedata=this.hs.getSourceData();
            //console.log(this.hs.getSourceData());
        },
        afterMergeCells(a,b,c){
            let isRepeat=false;
            for(let i in this.mergeCells){
                if (this.mergeCells[i].col==b.col &&
                    this.mergeCells[i].row==b.row &&
                    this.mergeCells[i].colspan==b.colspan &&
                    this.mergeCells[i].rowspan==b.rowspan){
                       isRepeat=true;
                }
            }
            if(!isRepeat){
                this.mergeCells.push(b);
            }
        },
        afterUnmergeCells(a,b,c){
            let tempCellRange={
                col:a.from.col,
                colspan:a.to.col-a.from.col+1,
                row:a.from.row,
                rowspan:a.to.row-a.from.row+1
            }
            for(let i in this.mergeCells){
                if(this.mergeCells[i].col==tempCellRange.col &&
                   this.mergeCells[i].row==tempCellRange.row &&
                   this.mergeCells[i].colspan==tempCellRange.colspan &&
                   this.mergeCells[i].rowspan==tempCellRange.rowspan){
                       this.mergeCells.splice(i,1);
                       console.log(i);
                       console.log('fasd',this.mergeCells);
                       break;
                }
            }
            console.log(a,b,c);
        },
        afterDocumentKeyDown(a){
            //console.log(a);//KeyboardEvent
        },
        afterSelection(a,b){
            this.setRowColNumber({
                row:a+1,
                col:b+1
            });
        },
        afterColumnResize(a,b){
            this.updateSize({
                index:this.index,
                data:{
                    type:'colWidths',
                    index:a,
                    value:b
                }
            });
        },
        afterRowResize(a,b){
            this.updateSize({
                index:this.index,
                data:{
                    type:'rowHeights',
                    index:a,
                    value:b
                }
            });

        }
    },
    components:{
        
    }
}
</script>


<style>
.st-table{
    overflow: auto;
}
::-webkit-scrollbar{
	width: 10px;
	background: #eee
}
::-webkit-scrollbar-thumb{ background: #6F6F6F }

</style>
